#include "out_fun.h"
#include <Arduino.h>
#include <nvs_flash.h>
#include "common_util.h"

//启动后out引脚的高地电平状态
uint8_t outDefs[2] = { 0, 0 };
char* outDefs_key[2] = { "o_d1_key", "o_d2_key" };
void outInit() {
  for (uint8_t i = 0; i < 2; i++) {
    nvs_get_u8(my_nvs_handle_t, outGios_key[i], &outGios[i]);
    nvs_get_u8(my_nvs_handle_t, outDefs_key[i], &outDefs[i]);
  }

  for (uint8_t i = 0; i < 2; i++) {
    if (outGios[i] < 99) {
      pinMode(outGios[i], OUTPUT);
      digitalWrite(outGios[i], outDefs[i]);
    }
    Serial.print("OUT_");
    Serial.print(i);
    Serial.print("_GIO:");
    Serial.print(outGios[i]);
    Serial.print("   SYS_O");
    Serial.print(i);
    Serial.println("G05");
    Serial.print("OUT_");
    Serial.print(i);
    Serial.print("_DEF:");
    Serial.print(outDefs[i]);
    Serial.print("   SYS_O");
    Serial.print(i);
    Serial.print("D0   SYS_O");
    Serial.print(i);
    Serial.println("D1");
  }
}

uint8_t requestOut(String request, int len) {
  if (!(request.startsWith("OUT_") || request.startsWith("out_"))) {
    return 0;
  }
  if (len < 5) {
    return 1;
  }
  uint8_t inedx = request.charAt(4) - '0';
  if (inedx > 1) {
    return 1;
  }
  if (len < 6) {
    return 1;
  }
  uint8_t c5 = request.charAt(5);
  if ((c5 == 'O' || c5 == 'o') && outGios[inedx] < 99 && len >= 7) {
    if (request.charAt(6) == '1') {
      digitalWrite(outGios[inedx], HIGH);
    } else {
      digitalWrite(outGios[inedx], LOW);
    }
    return 1;
  }
  if ((c5 == 'D' || c5 == 'd') && len >= 7) {
    Serial.print("Set new out ");
    Serial.print(inedx);
    Serial.print(" def:");
    if (request.charAt(6) == '1') {
      saveVlaueU8(outDefs_key[inedx], 1);
      Serial.println(1);
    } else {
      saveVlaueU8(outDefs_key[inedx], 0);
      Serial.println(0);
    }
    return 1;
  }
  if ((c5 == 'G' || c5 == 'g') && len >= 8) {
    Serial.print("Set new out ");
    Serial.print(inedx);
    Serial.print(" gio:");
    uint8_t gio = (request.charAt(6) - '0') * 10 + (request.charAt(7) - '0');
    saveVlaueU8(outGios_key[inedx], gio);
    Serial.println(gio);
    return 1;
  }
  return 1;
}